package leetcode.Top100;

import leetcode.ListNode;

/**
 * 2. 两数相加
 */
public class Top002_LC002 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null && l2==null) {
            return new ListNode(0);
        }
        ListNode head = new ListNode(0);
        ListNode cur = head;
        int demoValue = 0;
        add(l1, l2, cur, demoValue);
        return head.next;
    }

    public void add(ListNode l1, ListNode l2, ListNode cur, int demoValue) {
        if (l1==null && l2 == null) {
            if (demoValue != 0) {
                cur.next = new ListNode(demoValue);
            }
            return;
        }
        int l1Val = l1 != null ? l1.val : 0;
        int l2Val = l2 != null ? l2.val : 0;
        int sum = l1Val + l2Val + demoValue;
        cur.next = new ListNode(sum % 10);
        cur = cur.next;
        demoValue = sum / 10;
        add(l1!=null ? l1.next : null, l2!=null ? l2.next : null, cur, demoValue);
    }
}
